import 'dart:convert';

import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:megatron/utils/mydio.dart';
import 'package:megatron/utils/utils.dart';
import 'package:megatron/view/textfield.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../apis.dart';
import '../const.dart';
import '../routes.dart';

class Login extends StatefulWidget {
  final String pageIndex;

  Login({String pageIndex}) : this.pageIndex = pageIndex;

  @override
  _LoginState createState() => _LoginState(pageIndex: pageIndex);
}

class _LoginState extends State<Login> {
  String pageIndex;
  Map data = Map<String, String>();
  var _scaffoldkey = new GlobalKey<ScaffoldState>();
  SharedPreferences sp;

  _LoginState({String pageIndex}) : this.pageIndex = pageIndex;

  @override
  void initState() {
    requestPermission();
    checkLogin();
  }

  Future<bool> requestPermission() async {
    // final permissions = await PermissionHandler().requestPermissions([
    //   PermissionGroup.sensors,
    //   PermissionGroup.storage,
    //   PermissionGroup.microphone,
    //   PermissionGroup.speech,
    // ]);

    Map<Permission, PermissionStatus> statuses = await [
        Permission.sensors,
        Permission.storage,
        Permission.microphone,
        Permission.speech,
    ].request();
  }

  checkLogin() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String token = sharedPreferences.getString('token');
    if (!Utils.getInstance().checkEmpty(token)) {
      Routes.router.navigateTo(context, '${Routes.mainpage}',
          replace: true, transition: TransitionType.fadeIn);
    }
  }

  @override
  void dispose() {
    super.dispose();
    MyDio.getInstance().clearInstance();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      backgroundColor: const Color(0xffededed),
      key: _scaffoldkey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.fromLTRB(40, 96, 40, 0),
            child: Column(
              children: <Widget>[
                Image.asset(
                  'images/login_logo.png',
                  fit: BoxFit.fill,
                  scale: 3.3,
                ),
                SizedBox(
                  height: 49,
                ),
                EditText(
//                  keyboardType: TextInputType.number,
                  data: data,
                  name: 'username',
                  labelText: '请输入手机号',
                  value: Utils.getInstance().checkEmpty(data['username'])
                      ? ''
                      : data['username'],
                ),
                SizedBox(
                  height: 14,
                ),
                PassField(
                  labelText: '密码',
                  map: data,
                  mapKey: 'password',
                ),
                SizedBox(
                  height: 32,
                ),
                MaterialButton(
                  height: 44,
                  minWidth: MediaQuery.of(context).size.width,
                  elevation: 0,
                  onPressed: () {
                    Routes.router.navigateTo(context, '${Routes.mainpage}',
                        replace: true, transition: TransitionType.fadeIn);
                    /*if (data['username'] == null) {
                      Utils.getInstance().showSnackBar(_scaffoldkey, '用户名不能为空');
                      return;
                    }
                    if (data['password'] == null) {
                      Utils.getInstance().showSnackBar(_scaffoldkey, '密码不能为空');
                      return;
                    }
                    // 登录
                    MyDio.getInstance().clearInstance();
                    MyDio.getInstance().post(Apis.login, (data) async {
                      print(data);
                      sp = await SharedPreferences.getInstance();
                      sp.setString('token', data['token']);
                      Routes.router.navigateTo(context, '${Routes.mainpage}',
                          replace: true, transition: TransitionType.fadeIn);
                    }, errorCallBack: (error) async {
                      print('error:$error');
                      if (error == 404) {
                        Utils.getInstance()
                            .showSnackBar(_scaffoldkey, '用户名不存在');
                      } else if (error == 400) {
                        Utils.getInstance().showSnackBar(_scaffoldkey, '密码不正确');
                      }
                    }, params: data);*/
                  },
                  child: Text(
                    "登录",
                    style: TextStyle(color: Colors.white, fontSize: 18),
                  ),
                  color: Const.blue,
                  shape: RoundedRectangleBorder(
                      borderRadius:
                          BorderRadius.all(Radius.circular(88 / 3 * 2))),
                ),
              ],
            ),
          ),
          Image.asset('images/login_bg.png')
        ],
      ),
    );
  }

  String _md5Digest(String data) {
    var content = new Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    return hex.encode(digest.bytes);
  }
}
